package com.jadcon.addressbook.domain;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Component;

import com.jadcon.addressbook.util.DbUtils;

@Component("addressRepository")
public class AddressRepositoryImpl implements AddressRepository{
	private SimpleJdbcTemplate simpleJdbcTemplate = DbUtils.getSimpleJdbcTemplate();

	public List<Address> getAddressList() {
		String sql = "Select * from addressbook";
		List<Address> addressList = simpleJdbcTemplate.query(sql, new AddressRowMapper());
		return addressList;
	}

	public void save(Address address) {
		String sql = "insert into addressbook (name, address1, address2) values (?,?,?)";
		simpleJdbcTemplate.update(sql, address.getName(), address.getAddress1(), address.getAddress2());
	}
	
	private  final class AddressRowMapper implements RowMapper {

		public  Address mapRow(ResultSet rs, int rowNum) throws SQLException {
			String name = rs.getString("name");
			String address1 = rs.getString("address1");
			String address2 = rs.getString("address2");
			Address address = new Address();
			address.setName(name);
			address.setAddress1(address1);
			address.setAddress2(address2);
			return address;
		}
		
	}
	
	

}
